<template>
  <div class="equipment-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>设备列表</span>
          <div>
            <el-button
              type="primary"
              :disabled="selectedDevices.length === 0"
              @click="handleDeviceManagement"
            >
              设备管理
            </el-button>
            <el-button type="primary" icon="Upload" @click="handleImport"
              >导入Excel</el-button
            >
          </div>
        </div>
      </template>

      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="120px"
      >
        <el-form-item label="设备名称111" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入设备名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="deviceStatus">
          <el-select
            v-model="queryParams.deviceStatus"
            placeholder="请选择设备状态"
            clearable
            style="width: 200px"
          >
            <el-option label="暂停" :value="100" />
            <el-option label="运行中" :value="200" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前温度" prop="currentTemperatureMin">
          <el-input
            v-model="queryParams.currentTemperatureMin"
            placeholder="最小值"
            class="temperature-range"
            type="number"
          />
          <span class="temperature-separator">-</span>
          <el-input
            v-model="queryParams.currentTemperatureMax"
            placeholder="最大值"
            class="temperature-range"
            type="number"
          />
        </el-form-item>
        <el-form-item label="设备风速" prop="windSpeed">
          <el-select
            v-model="queryParams.windSpeed"
            placeholder="请选择风速"
            clearable
            style="width: 200px"
          >
            <el-option label="低速" :value="0" />
            <el-option label="中速" :value="1" />
            <el-option label="高速" :value="2" />
            <el-option label="自动" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备模式" prop="pattern">
          <el-select
            v-model="queryParams.pattern"
            placeholder="请选择模式"
            clearable
            style="width: 200px"
          >
            <el-option label="制冷" :value="100" />
            <el-option label="制热" :value="200" />
            <el-option label="送风" :value="300" />
          </el-select>
        </el-form-item>
        <el-form-item label="制冷温度" prop="cryogenicTemperatureMin">
          <el-input
            v-model="queryParams.cryogenicTemperatureMin"
            placeholder="最小值"
            class="temperature-range"
            type="number"
          />
          <span class="temperature-separator">-</span>
          <el-input
            v-model="queryParams.cryogenicTemperatureMax"
            placeholder="最大值"
            class="temperature-range"
            type="number"
          />
        </el-form-item>
        <el-form-item label="制热温度" prop="heatingTemperatureMin">
          <el-input
            v-model="queryParams.heatingTemperatureMin"
            placeholder="最小值"
            class="temperature-range"
            type="number"
          />
          <span class="temperature-separator">-</span>
          <el-input
            v-model="queryParams.heatingTemperatureMax"
            placeholder="最大值"
            class="temperature-range"
            type="number"
          />
        </el-form-item>
        <el-form-item label="按键锁定状态" prop="keyLock">
          <el-select
            v-model="queryParams.keyLock"
            placeholder="请选择锁定状态"
            clearable
            style="width: 200px"
          >
            <el-option label="未锁定" :value="0" />
            <el-option label="锁定" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="deviceList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="deviceName" label="设备名称" min-width="120" />
        <el-table-column prop="alias" label="设备别名" min-width="100" />
        <el-table-column
          prop="equipmentAmount"
          label="设备金额"
          min-width="100"
        >
          <template #default="scope">
            {{
              scope.row.equipmentAmount ? `¥${scope.row.equipmentAmount}` : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceStatus" label="设备状态" min-width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.deviceStatus)">
              {{ getStatusText(scope.row.deviceStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="currentTemperature"
          label="当前温度"
          min-width="100"
        >
          <template #default="scope">
            {{
              scope.row.currentTemperature
                ? `${scope.row.currentTemperature}°C`
                : "-"
            }}
          </template>
        </el-table-column>
        <el-table-column prop="windSpeed" label="风速" min-width="80">
          <template #default="scope">
            {{ getWindSpeedText(scope.row.windSpeed) }}
          </template>
        </el-table-column>
        <el-table-column prop="pattern" label="模式" min-width="80">
          <template #default="scope">
            {{ getPatternText(scope.row.pattern) }}
          </template>
        </el-table-column>
        <el-table-column prop="isOpen" label="开关状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isOpen ? 'success' : 'danger'">
              {{ scope.row.isOpen ? "开启" : "关闭" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="mac" label="MAC地址" min-width="140" />
        <el-table-column prop="userInfo.organization" label="所属组织" />
        <el-table-column prop="userInfo.cardNumber" label="用户卡号" />
        <el-table-column prop="userInfo.name" label="用户姓名" />
        <el-table-column prop="userInfo.address" label="用户地址" />
        <el-table-column prop="userInfo.year" label="供暖年度" />
        <el-table-column prop="userInfo.area" label="应收面积" />
        <el-table-column prop="userInfo.price" label="单价" />
        <el-table-column prop="userInfo.feeMethod" label="计费方式" />
        <el-table-column prop="userInfo.fee" label="收费金额" />
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="lockDevice(scope)">{{
              scope.row.keyLock == "unLock" ? "锁定" : "解锁"
            }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div :class="{ hidden: hidden }" class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 50, 100, 500, 1000]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 设备管理弹窗 -->
    <el-dialog
      v-model="deviceManagementVisible"
      title="设备管理"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="device-management-content">
        <!-- <div class="selected-devices">
          <h4>已选择的设备：</h4>
          <el-tag 
            v-for="device in selectedDevices" 
            :key="device.mac"
            class="device-tag"
            type="info"
          >
            {{ device.deviceName || device.mac }}
          </el-tag>
        </div> -->
        
        <div class="temperature-settings">
          <h4>温度设定：</h4>
          <el-form :model="{ maxTemp: maxTemperature, minTemp: minTemperature }" label-width="100px">
            <el-form-item label="最大温度：">
              <el-input
                v-model="maxTemperature"
                type="number"
                placeholder="请输入最大温度"
                clearable
              />
            </el-form-item>
            <el-form-item label="最小温度：">
              <el-input
                v-model="minTemperature"
                type="number"
                placeholder="请输入最小温度"
                clearable
              />
            </el-form-item>
          </el-form>
          <p class="temp-tip">注意：可以只设置最大值或最小值，也可以同时设置</p>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deviceManagementVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTemperatureSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getDeviceList,
  setDeviceStatus,
  setDeviceTemperature,
} from "@/api/equipmentManagement/equipmentList";
import { uploadFile } from "@/api/file";

const queryParams = reactive({
  name: "",
  deviceStatus: null,
  currentTemperatureMin: null,
  currentTemperatureMax: null,
  windSpeed: null,
  pattern: null,
  cryogenicTemperatureMin: null,
  cryogenicTemperatureMax: null,
  heatingTemperatureMin: null,
  heatingTemperatureMax: null,
  keyLock: null,
  pageNum: 1,
  pageSize: 10,
});

const deviceList = ref([]);
const total = ref(0);
const loading = ref(false);
const queryRef = ref();
const hidden = ref(false);
const selectedDevices = ref([]);

const getList = async () => {
  loading.value = true;
  try {
    const params = {
      name: queryParams.name,
      deviceStatus: queryParams.deviceStatus,
      currentTemperatureMin: queryParams.currentTemperatureMin,
      currentTemperatureMax: queryParams.currentTemperatureMax,
      windSpeed: queryParams.windSpeed,
      pattern: queryParams.pattern,
      cryogenicTemperatureMin: queryParams.cryogenicTemperatureMin,
      cryogenicTemperatureMax: queryParams.cryogenicTemperatureMax,
      heatingTemperatureMin: queryParams.heatingTemperatureMin,
      heatingTemperatureMax: queryParams.heatingTemperatureMax,
      keyLock: queryParams.keyLock,
      SkipCount: (queryParams.pageNum - 1) * queryParams.pageSize,
      MaxResultCount: queryParams.pageSize,
    };

    // 过滤掉空值
    Object.keys(params).forEach((key) => {
      if (
        params[key] === null ||
        params[key] === undefined ||
        params[key] === ""
      ) {
        delete params[key];
      }
    });

    const response = await getDeviceList(params);
    console.log("设备列表响应:", response);

    const responseData = response.data || response;
    deviceList.value = responseData.datas || [];
    total.value = responseData.total?.value || 0;

    console.log("设备列表数据:", deviceList.value);
  } catch (error) {
    console.error("获取设备列表失败:", error);
    ElMessage.error("获取设备列表失败");
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryRef.value?.resetFields();
  Object.keys(queryParams).forEach((key) => {
    if (key !== "pageNum" && key !== "pageSize") {
      queryParams[key] = null;
    }
  });
  queryParams.pageNum = 1;
  getList();
};

const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedDevices.value = selection;
};

// 设备管理弹窗
const deviceManagementVisible = ref(false);
const maxTemperature = ref('');
const minTemperature = ref('');

const handleDeviceManagement = () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning("请先选择设备");
    return;
  }
  
  // 重置温度输入
  maxTemperature.value = '';
  minTemperature.value = '';
  deviceManagementVisible.value = true;
};

// 保存温度设定
const saveTemperatureSettings = async () => {
  if (!maxTemperature.value && !minTemperature.value) {
    ElMessage.warning('请至少设置一个温度值');
    return;
  }
  
  if (maxTemperature.value && minTemperature.value && 
      parseInt(maxTemperature.value) <= parseInt(minTemperature.value)) {
    ElMessage.warning('最大温度必须大于最小温度');
    return;
  }
  
    const requestData = selectedDevices.value.map(device => ({
      mac: device.mac,
      max: maxTemperature.value ? parseInt(maxTemperature.value) : null,
      min: minTemperature.value ? parseInt(minTemperature.value) : null,
    }));
    
    const response = await setDeviceTemperature(requestData);
    console.log("温度设定响应:", response);
    if (response.data.succeedNum > 0) {
      const message = `温度设定成功：成功${response.data.succeedNum}条${response.data.loseNum > 0 ? `，失败${response.data.loseNum}条` : ''}`;
      ElMessage.success(message);
      getList();
      deviceManagementVisible.value = false;
    } else {
      ElMessage.error('温度设定失败');
    }
};

const getStatusType = (status) => {
  const statusMap = {
    pause: "warning",
    operation: "success",
    error: "danger",
    offline: "info",
  };
  return statusMap[status] || "info";
};

const getStatusText = (status) => {
  const statusMap = {
    pause: "暂停",
    operation: "运行中",
    error: "错误",
    offline: "离线",
  };
  return statusMap[status] || status;
};

const getWindSpeedText = (windSpeed) => {
  const windSpeedMap = {
    low: "低速",
    medium: "中速",
    high: "高速",
    auto: "自动",
  };
  return windSpeedMap[windSpeed] || windSpeed;
};

const getPatternText = (pattern) => {
  const patternMap = {
    cooling: "制冷",
    heating: "制热",
    fan: "送风",
    auto: "自动",
  };
  return patternMap[pattern] || pattern;
};

const lockDevice = async (scoped) => {
  console.log(11);
  setDeviceStatus({
    mac: scoped.row.mac,
    command: scoped.row.keyLock == "unLock" ? 8 : 7,
  });
};

// 导入Excel文件
const handleImport = () => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = ".xlsx,.xls";
  input.onchange = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    try {
      const formData = new FormData();
      formData.append("file", file);

      const response = await uploadFile("/device-user/excel-import", formData);

      if (response.success == true) {
        ElMessage.success(response.message || "导入成功");
        getList();
      } else {
        ElMessage.error(response.message || "导入失败");
      }
    } catch (error) {
      console.error("导入失败:", error);
      ElMessage.error("导入失败");
    }
  };
  input.click();
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.equipment-list-container {
  .box-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
    }

    .el-form {
      margin-bottom: 20px;

      .el-form-item {
        margin-bottom: 15px;

        .el-input {
          &.temperature-range {
            width: 100px;
          }
        }

        .temperature-separator {
          margin: 0 8px;
          color: #909399;
        }
      }
    }

    .el-table {
      margin-bottom: 20px;
    }
  }
}

// 设备管理弹窗样式
.device-management-content {
  .selected-devices {
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 10px 0;
      color: #303133;
    }
    
    .device-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }
  
  .temperature-settings {
    border-top: 1px solid #e4e7ed;
    padding-top: 15px;
    
    h4 {
      margin: 0 0 15px 0;
      color: #303133;
    }
    
    .temp-tip {
      margin: 10px 0 0 0;
      font-size: 12px;
      color: #909399;
      font-style: italic;
    }
  }
}
</style>
